package com.azr.jesus.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.azr.jesus.common.domain.HttpStatus;
import com.azr.jesus.entity.User;
import com.azr.jesus.exception.ServiceException;
import com.azr.jesus.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT拦截器
 * @author:: Xiong
 * @date:: 2022/11/17 21:41
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从http请求头中取出token
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return Boolean.TRUE;
        }
        // 执行认证
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(HttpStatus.UNAUTHORIZED, "无token，请登录认证！");
        }
        // 获取token中的userId
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new ServiceException(HttpStatus.UNAUTHORIZED, "token验证失败，请重新登录！");
        }
        User user = userService.getById(userId);
        if (user == null) {
            throw new ServiceException(HttpStatus.UNAUTHORIZED, "用户不存在，请重新登录!");
        }
        // 用户密码加签验证token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ServiceException(HttpStatus.UNAUTHORIZED, "token验证失败，请重新登录！");
        }
        return Boolean.TRUE;
    }
}
